<template>
  <custom-dialog
    ref="dialog"
    title="设置菜单" width="66%" height="500px"
    :before-confirm="beforeConfirm" :on-confirm="onConfirm"
  >
    <div class="padding" v-for="item in treeData" :key="item.id">
      <block-title :title="item.applicationName"></block-title>
      <el-tree
        class="margin-top-10"
        ref="tree"
        node-key="id"
        :default-checked-keys="checkedKeys"
        :data="item.list"
        check-strictly
        default-expand-all
        show-checkbox
        :props="{
        label: 'menuTitle',
        children: 'children',
        isLeaf: 'isLeaf'
      }"
      ></el-tree>
    </div>
  </custom-dialog>
</template>

<script>
import CustomDialog from '@/components/custom-dialog'
import BlockTitle from '@/components/block-title'
import { queryApplicationMenu } from '@/api/sysRoleApplication'
import { batchByRoleMenu, loadByRoleMenuList } from '@/api/sysRoleMenu'

const api = {
  queryApplicationMenu,
  batchByRoleMenu,
  loadByRoleMenuList
}
export default {
  name: 'set-menu-modal',
  props: {
    roleId: {
      type: [String, Number],
      required: true
    }
  },
  components: {
    BlockTitle,
    CustomDialog
  },
  data () {
    return {
      checkedKeys: [],
      menuIds: [],
      treeData: []
    }
  },
  methods: {
    getMenuIdsByRoleId () {
      return api.loadByRoleMenuList(this.roleId).then(res => {
        if (res.code === 200) {
          this.checkedKeys = res.data
          return res.data
        }
      })
    },
    getMenus () {
      return api.queryApplicationMenu().then(res => {
        if (res.code === 200) {
          res.data.forEach(v => {
            v.isLeaf = !(v.children && v.children.length > 0)
          })
          this.treeData = res.data
        }
      })
    },
    open () {
      this.menuIds = []
      this.getMenus()
      this.getMenuIdsByRoleId()
      this.$nextTick(() => {
        this.$refs.dialog.open()
      })
    },
    beforeConfirm () {
      let menuIds = []
      const trees = this.$refs.tree
      trees.forEach(tree => {
        menuIds = menuIds.concat(tree.getCheckedKeys())
      })
      if (menuIds.length < 1) {
        this.$message.error('请勾选菜单')
      } else {
        this.menuIds = menuIds
      }
      return menuIds.length > 0
    },
    onConfirm (close) {
      const menuIds = this.menuIds
      const params = menuIds.map(v => ({
        roleId: this.roleId,
        menuId: v
      }))
      return api.batchByRoleMenu(params).then(res => {
        if (res.code === 200) {
          this.$emit('save-success')
          this.$message.success('保存成功')
          close()
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
